#include "SpriteBrick.h"

SpriteBrick::SpriteBrick(char* aNormalName,char* aDragName)
{
	m_normalTextureName = aNormalName;
	m_dragTextureName = aDragName;
}

SpriteBrick::~SpriteBrick(void)
{
}

CCRect SpriteBrick::rect()
{
	CCSize s = getTexture()->getContentSize();
	return CCRectMake(0, -s.height, s.width, s.height);
}

SpriteBrick* SpriteBrick::CreateWithTexture(char* aNormalName,char* aDragName)
{	
	SpriteBrick* pSpriteBrick = new SpriteBrick(aNormalName,aDragName);
	pSpriteBrick->autorelease();

	CCTextureCache::sharedTextureCache()->addImage(aDragName);
	CCTexture2D* spriteBrickTexture = CCTextureCache::sharedTextureCache()->addImage(aNormalName);

	pSpriteBrick->initWithTexture(spriteBrickTexture);
	return pSpriteBrick;
}

bool SpriteBrick::initWithTexture(CCTexture2D* aTexture)
{
	if( CCSprite::initWithTexture(aTexture) ) 
	{
		m_state = kSpriteBrickUngrabbed;
	}

	return true;
}

void SpriteBrick::onEnter()
{
	CCDirector* pDirector = CCDirector::sharedDirector();
	pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
	CCSprite::onEnter();
}

void SpriteBrick::onExit()
{
	CCDirector* pDirector = CCDirector::sharedDirector();
	pDirector->getTouchDispatcher()->removeDelegate(this);
	CCSprite::onExit();
}    

bool SpriteBrick::containsTouchLocation(CCTouch* touch)
{
	return rect().containsPoint(convertTouchToNodeSpaceAR(touch));
}

bool SpriteBrick::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
	if (m_state != kSpriteBrickUngrabbed) return false;
	if ( !containsTouchLocation(touch) ) return false;
	m_state = kSpriteBrickGrabbed;

	this->setTexture( CCTextureCache::sharedTextureCache()->textureForKey(m_dragTextureName));

	fireTouchBeginEvent(event);
	return true;
}

void SpriteBrick::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
	CCAssert(m_state == kSpriteBrickGrabbed, "SpriteBrick - Unexpected state!");    

	CCPoint touchPoint = touch->getLocation();
	fireTouchMoveEvent(touchPoint,event);
}

void SpriteBrick::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
	CCAssert(m_state == kSpriteBrickGrabbed, "SpriteBrick - Unexpected state!");    	
	m_state = kSpriteBrickUngrabbed;
	
	this->setTexture( CCTextureCache::sharedTextureCache()->textureForKey(m_normalTextureName));

	fireTouchEndEvent(event);
}

CCObject* SpriteBrick::copyWithZone(CCZone *pZone)
{
	this->retain();
	return this;
}